package cn.edu.sjtu.se.dslab.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

import org.apache.log4j.Logger;

/**
 * Change the encoding of the file
 * 
 * @author thinker
 * 
 */
public class EncodingUtil {
	private static final Logger logger = Logger.getLogger(EncodingUtil.class);

	private static final String GBK = "GBK";
	private static final String UTF_8 = "UTF-8";

	private static EncodingUtil instance;

	private EncodingUtil() {

	}

	public static EncodingUtil getInstance() {
		if (instance == null) {
			instance = new EncodingUtil();
		}
		return instance;
	}

	public void changeDirToGBK(String dirPath) {

	}

	public void changeDirToUTF8(String dirPath) {

	}

	public void changeDirectoryEncoding(String srcDirPath, String tagDirPath,
			String encoding) {
		File directory = new File(srcDirPath);
		if (!directory.exists()) {
			logger.info("Directory not exist:" + srcDirPath);
			return;
		}

		for (File f : directory.listFiles()) {
			if (f.isFile()) {
				StringBuilder filePath = new StringBuilder(tagDirPath);
				filePath.append(f.getName());
				logger.info("Change File Encoding...");
				changeEncoding(f.getAbsolutePath(), filePath.toString(),
						encoding);
			} else if (f.isDirectory()) {
				logger.info(f.getAbsolutePath());
				changeDirectoryEncoding(srcDirPath, tagDirPath + f.getName(), encoding);
			}
		}

	}

	public void toUTF8(String srcFilePath, String tagFilePath) {
		changeEncoding(srcFilePath, tagFilePath, UTF_8);
	}

	public void toGBK(String srcFilePath, String tagFilePath) {
		changeEncoding(srcFilePath, tagFilePath, GBK);
	}

	public void changeEncoding(String srcFilePath, String tagFilePath,
			String encoding) {
		File srcFile = new File(srcFilePath); // 获取文件
		File tagFile = new File(tagFilePath);// 转码后保存在这文件里

		BufferedReader reader = null;
		BufferedWriter writer = null;
		try {
			reader = new BufferedReader(new FileReader(srcFile));

			if (!tagFile.exists()) {
				tagFile.createNewFile();
			}

			writer = new BufferedWriter(new FileWriter(tagFile));

			String str;
			while ((str = reader.readLine()) != null) {
				writer.write(new String(str.getBytes(), encoding));// 指定转码格式
			}

		} catch (FileNotFoundException e) {
			logger.error("Source file not found !" + e.getMessage());
		} catch (IOException e) {
			logger.error("IO Exception !!");
		} finally {
			try {
				if (reader != null)
					reader.close();
				if (writer != null)
					writer.close();
			} catch (IOException e) {
				e.printStackTrace();
			}

		}
	}
}
